package com.xydtech.common.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 时间工具类
 *
 * @author xydtech
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmssSSS";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYMMDDHHMM = "yyMMddHHmm";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeSim() {
        return dateTimeNow(YYMMDDHHMM);
    }

    public static final String dateMillisecondNow() {
        return dateTimeNow(YYYYMMDDHHMMSSSSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    //获取汉字年月日
    public static final String bigDateTime(final Date date) {
        if (date == null) {
            return "";
        }
        String[] dateArry = parseDateToStr(YYYY_MM_DD, date).split("-");
        return dateArry[0] + "年" + dateArry[1] + "月" + dateArry[2] + "日";
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 计算相差秒数
     */
    public static int differentsecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / 1000));
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     *日期格式转换为指定格式日期
     * @Title: formatDate
     * @param date
     * @param pattern parsePatterns
     * @return java.util.Date
     * @exception
     * @author JHON
     * @Date 2023/3/24 15:07
     **/
    public static Date formatDate(Date date, String pattern) {
        return parseDate(DateFormatUtils.format(date, pattern));
    }

    /**
     *当前年份
     * @Title: getYear
     * @return java.lang.String
     * @exception
     * @author JHON
     * @Date 2022/5/10 11:25
     **/
    public static String getYear() {
        return dateTimeNow(YYYY);
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }



    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDateForDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns[0]);
        } catch (ParseException e) {
            return null;
        }
    }


    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数的绝对值
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }


    /**
     * 计算date2-date1的实际相差天数
     * 如date2>date1,那么返回正数
     * 如date2=date1,那么返回0
     * 如date2<date1,那么返回负数
     */
    public static int differentDaysByActualMillisecond(Date date1, Date date2) {
        return (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
    }

    /**
     * 计算相差整月数(不足一月的舍去)
     */
    public static Integer getDifMonth(Date startDate, Date endDate) {
        Period period = Period.between(LocalDate.parse(dateTime(startDate)), LocalDate.parse(dateTime(endDate)));

        return period.getYears() * 12 + period.getMonths();
    }

    /**
     * 计算相差月数
     */
    public static Integer getDifMonths(Date startDate, Date endDate) {
        Period period = Period.between(LocalDate.parse(dateTime(startDate)), LocalDate.parse(dateTime(endDate)));
        Integer months = period.getYears() * 12 + period.getMonths();
        if (getNextMonth(startDate, months).before(endDate)) {
            return months + 1;
        }
        return months;
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 校验是否为日期格式的字符串
     * @Title isDate
     * @param
     * @return boolean
     * @exception
     * @author Daniel
     * @Date 2020/6/18 8:51
     **/
    public static boolean isDate(String str) {
        String pattern = "([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))";
        boolean isMatch = Pattern.matches(pattern, str);
        return isMatch;
    }

    /**
     * 根据传入时间获取上月/上年时间
     * @Title getLastMonth
     * @param type Calendar.MONTH/Calendar.YEAR
     * @param inputDate
     * @param format
     * @return java.lang.String
     * @exception
     * @author Daniel
     * @Date 2020/5/19 17:26
     **/
    public static String getLastMonthOrYear(int type, Date inputDate, String format) {
        if (inputDate == null) {
            inputDate = new Date();
        }

        if (StringUtils.isEmpty(format)) {
            format = YYYY_MM_DD;
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(inputDate);

        calendar.add(type, -1);

        return parseDateToStr(format, calendar.getTime());
    }

    public static Map<String,Integer> getDateDetails(Date fromDate, Date toDate){

        if(fromDate == null || toDate == null){
            return null;
        }

        Map<String,Integer> map = null;
        try {

            //String text1 = "2022-01-29";
            Temporal startDate = LocalDate.parse(dateTime(fromDate));
            //String text2 = "2023-12-31";
            Temporal endDate = LocalDate.parse(dateTime(toDate));
            int years = (int)ChronoUnit.YEARS.between(startDate,endDate);
            int month = (int)ChronoUnit.MONTHS.between(startDate,endDate);
            int days = (int)ChronoUnit.DAYS.between(startDate,endDate);

            map = new HashMap<>();
            map.put("years",years);
            map.put("month",month);
            map.put("days",days);

        }catch (Exception e){
            e.printStackTrace();
        }
        return map;

    }



    public static Map<String,Integer> getDateDetailsStr(String fromDate, String toDate){

        if(StringUtils.isBlank(fromDate) || StringUtils.isBlank(toDate)){
            return null;
        }

        Map<String,Integer> map = null;
        try {

            //String text1 = "2022-01-29";
            Temporal startDate = LocalDate.parse(fromDate);
            //String text2 = "2023-12-31";
            Temporal endDate = LocalDate.parse(toDate);
            int years = (int)ChronoUnit.YEARS.between(startDate,endDate);
            int month = (int)ChronoUnit.MONTHS.between(startDate,endDate);
            int days = (int)ChronoUnit.DAYS.between(startDate,endDate);

            map = new HashMap<>();
            map.put("years",years);
            map.put("month",month);
            map.put("days",days);

        }catch (Exception e){
            e.printStackTrace();
        }
        return map;

    }


    /**
     *根据传入时间获取下月
     * @Title: getNextMonth
     * @param inputDate 日期
     * @param months 月数
     * @return java.util.Date
     * @exception
     * @author JHON
     * @Date 2022/1/26 16:05
     **/
    public static Date getNextMonth(Date inputDate, int months) {
        if (inputDate == null) {
            inputDate = new Date();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(inputDate);
        calendar.add(Calendar.MONTH, months);
        return calendar.getTime();
    }

    /**
     *根据传入时间获取下一天
     * @Title: getNextDay
     * @param inputDate 日期
     * @param days 天数
     * @return java.util.Date
     * @exception
     * @author JHON
     * @Date 2022/1/26 16:05
     **/
    public static Date getNextDay(Date inputDate, int days) {
        if (inputDate == null) {
            inputDate = new Date();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(inputDate);
        calendar.add(Calendar.DATE, days);
        return calendar.getTime();
    }

    /**
     *时间戳转换为日期格式
     * @Title: timeStamp2Date
     * @param time parsePatterns
     * @return java.lang.String
     * @exception
     * @author JHON
     * @Date 2022/6/13 15:35
     **/
    public static String timeStamp2Date(String time) {
        Long timeLong = Long.parseLong(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//要转换的时间格式
        Date date;
        try {
            date = sdf.parse(sdf.format(timeLong));
            return sdf.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 公共方法:处理日期,补日期数据
     * TODO:二月/闰年/29号/30号/31号   eg:localDateNext会返回一个新的localDateNext
     */
    public static LocalDate dateInitCheckFtpDataProcess(LocalDate localDateInit,LocalDate localDateNext){

        int localDateMonthNext = localDateNext.getMonth().getValue();
        if (localDateMonthNext != 2) {
            int localDateDayCurrent = localDateInit.getDayOfMonth();
            int localDateDayNext = localDateNext.getDayOfMonth();
            if(localDateDayCurrent > 30 && localDateDayNext == 30){
                localDateNext = LocalDate.of(localDateNext.getYear(),localDateMonthNext + 1,localDateDayCurrent - localDateDayNext);
            }
        } else {
            int localDateDayCurrent = localDateInit.getDayOfMonth();
            if (localDateDayCurrent > 28) {
                int localDateDayNext = localDateNext.getDayOfMonth();
                int difference = localDateDayCurrent - localDateDayNext;
                int localDateYearNext = localDateNext.getYear();
                if ((localDateYearNext % 4 == 0 && localDateYearNext % 100 != 0) || localDateYearNext % 400 == 0) {
                    if(difference > 0){
                        localDateNext = LocalDate.of(localDateYearNext,3,difference);
                    }
                }else{
                    localDateNext = LocalDate.of(localDateYearNext,3,difference);
                }
            }
        }
        return localDateNext;
    }

    /**
     * 根据截止日期和天数倒推起始日期
     * @param endDate
     * @param days
     * @return
     */
    public static LocalDate calculateStartDate(Date endDate, long days) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = formatter.format(endDate);
        LocalDate localDate = LocalDate.parse(formattedDate);
        return localDate.minusDays(days);
    }

    /**
     * 根据传入日期获取上一个工作日日期
     * @param dateSerch
     * @return
     */
    public static String getLastWeekDay(String dateSerch){
        Date date = DateUtils.parseDate(dateSerch);
        int month = date.getMonth();
        int day = date.getDate();
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        int today = now.getTime().getDay();//取得今天的星期值
        if(today == now.getFirstDayOfWeek()){//今天在这个星期中是否为第一天
            now.roll(Calendar.DAY_OF_YEAR, -3);
        } else if(today == 0){//周天
            now.roll(Calendar.DAY_OF_YEAR, -2);
        } else{
            now.roll(Calendar.DAY_OF_YEAR, -1);
        }
        //跨年问题
        if (month == 0 && day == 1){
            now.add(Calendar.YEAR, -1);
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.YYYY_MM_DD);
        return sdf.format(now.getTime());
    }
    public static void main(String[] args) {
        System.out.println(formatDate(parseDate("2023-09-11"), "yyyy-MM").compareTo(formatDate(parseDate("2023-09-20"), "yyyy-MM")));

    }
}
